package org.seed.mybatis.springboot.util;


import cn.hutool.json.JSONUtil;
import org.apache.ibatis.mapping.BoundSql;
import org.burgeon.commons.runtime.ThreadContextHolder;
import org.seed.mybatis.springboot.scatter.DataSourceContext;

import java.text.DecimalFormat;

public class SqlLogger {


    public static void log(BoundSql boundSql, long durationMs) {
        try {
            String newSql = boundSql.getSql();
            newSql = newSql.replace("\n", " ");
            newSql = newSql.replaceAll("\\s+", " ");
            String elapsed = null;
            DecimalFormat df = new DecimalFormat("#.##");
            if (durationMs > 1000L) {
                elapsed = df.format((double) durationMs / (double) 1000.0F) + " s";
            } else {
                elapsed = String.valueOf(durationMs) + " ms";
            }

            System.out.println("\n╔═════════════════════════════════════╗\n" +
                    " ➜ TraceId: {" + ThreadContextHolder.getTraceId() + "}\n" +
                    " ➜ DataSource: {" + DataSourceContext.getDataSourceKey() + "}\n" +
                    " ➜ SQL: {" + newSql + "}\n" +
                    " ➜ Parameter: {" + JSONUtil.toJsonStr(boundSql.getParameterObject()) + "}\n" +
                    " ➜ Elapsed: {" + elapsed + "}\n" +
                    "╚═════════════════════════════════════╝");
        } catch (Exception ignored) {
        }
    }

}
